#include "rtconfig.h"
#include "rtthread.h"
#include <rtdevice.h>
#include "finsh.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <dfs_file.h>
#include <unistd.h>
#include <fcntl.h>

static void spiflushtest(int argc, char **args)
{
    int ret;
    uint8_t *pdata = (uint8_t*)malloc(2048);
    if(pdata == NULL)
    {
        printf("Malloc data memory failed!!!\r\n");
        return;
    }

    char filename[64] = {0};

    mkdir("/spiflash/sfudtest", 0);
    
    for(int i=0; i<10; i++)
    {
        snprintf(filename, 64, "/spiflash/sfudtest/test%d.bin", i);
        FILE *fp = fopen(filename, "w+");
        if(fp == NULL)
        {
            printf("Create file %s failed!\r\n", filename);
            continue;
        }

        memset(pdata, 2*i, 2048);
        ret = fwrite(pdata, 1, 2048, fp);
        if(ret != 2048)
        {
            printf("Write file %s failed: %d\r\n", filename, ret);
        }

        fclose(fp);
    }

    for(int i=0; i<10; i++)
    {
        snprintf(filename, 64, "/spiflash/sfudtest/test%d.bin", i);
        FILE *fp = fopen(filename, "r+");
        if(fp == NULL)
        {
            printf("Create file %s failed!\r\n", filename);
            continue;
        }

        ret = fread(pdata, 1, 2048, fp);
        if(ret != 2048)
        {
            printf("Read file %s failed: %d\r\n", filename, ret);
        }

        for(int j=0; j<2048; j++)
        {
            if(pdata[j] != i*2)
            {
                printf("Data compare failed: %s\r\n", filename);
                break;
            }
        }

        fclose(fp);
    }

    free(pdata);
}


MSH_CMD_EXPORT_ALIAS(spiflushtest, spiflushtest, This is a spi flush test!);
